<template>
  <div class="userManagePage">
    <!-- 搜索表单 -->
    <a-form :model="searchParams" layout="inline" @finish="doSearch">
      <a-form-item label="账号">
        <a-input v-model:value="searchParams.userAccount" placeholder="输入账号" />
      </a-form-item>
      <a-form-item label="用户名">
        <a-input v-model:value="searchParams.userName" placeholder="输入用户名" />
      </a-form-item>
      <a-form-item>
        <a-button html-type="submit" type="primary">搜索</a-button>
      </a-form-item>
    </a-form>
    <a-divider />
    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="data"
      :pagination="pagination"
      @change="doTableChange"
    >
      <template #headerCell="{ column }">
        <template v-if="column.key === 'name'">
          <span>
            <smile-outlined />
            Name
          </span>
        </template>
      </template>

      <template #bodyCell="{ column, record }">
        <!-- 用户名可编辑 -->
        <template v-if="column.dataIndex === 'userName'">
          <div v-if="editingKey === record.id">
            <a-input v-model:value="editableRow.userName" placeholder="请输入用户名" />
          </div>
          <div v-else>
            {{ record.userName }}
          </div>
        </template>
        <!-- 简介可编辑 -->
        <template v-else-if="column.dataIndex === 'userProfile'">
          <div v-if="editingKey === record.id">
            <a-input v-model:value="editableRow.userProfile" placeholder="请输入简介" />
          </div>
          <div v-else>
            {{ record.userProfile }}
          </div>
        </template>
        <template v-if="column.dataIndex === 'userAvatar'">
          <a-image :src="record.userAvatar" :width="120" />
        </template>
        <template v-else-if="column.dataIndex === 'userRole'">
          <div v-if="editingKey === record.id" style="min-width: 120px">
            <a-select v-model:value="editableRow.userRole" style="width: 120px">
              <a-select-option value="user">普通用户</a-select-option>
              <a-select-option value="admin">管理员</a-select-option>
            </a-select>
          </div>
          <div v-else>
            <div v-if="record.userRole === 'admin'">
              <a-tag color="green">管理员</a-tag>
            </div>
            <div v-else>
              <a-tag color="blue">普通用户</a-tag>
            </div>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.key === 'action'">
          <template v-if="editingKey === record.id">
            <a-space>
              <a-button type="primary" @click="onSave(record.id)">保存</a-button>
              <a-button @click="onCancel">取消</a-button>
            </a-space>
          </template>
          <template v-else>
            <a-space>
              <a-button @click="onEdit(record)">编辑</a-button>
              <a-button danger @click="doDelete(record.id)">删除</a-button>
            </a-space>
          </template>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { deleteUser, listUserVoByPage, updateUser } from '@/api/userController.ts'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
  },
  {
    title: '账号',
    dataIndex: 'userAccount',
  },
  {
    title: '用户名',
    dataIndex: 'userName',
  },
  {
    title: '头像',
    dataIndex: 'userAvatar',
  },
  {
    title: '简介',
    dataIndex: 'userProfile',
  },
  {
    title: '用户角色',
    dataIndex: 'userRole',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]

// 数据
const data = ref<API.UserVO[]>([])
const total = ref(0)

// 搜索条件
const searchParams = reactive<API.UserQueryRequest>({
  pageNum: 1,
  pageSize: 10,
})

// 获取数据
const fetchData = async () => {
  const res = await listUserVoByPage({
    ...searchParams,
  })
  if (res.data.data) {
    data.value = res.data.data.records ?? []
    total.value = res.data.data.totalRow ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

// 行内编辑状态
const editingKey = ref<number | null>(null)
const editableRow = reactive<{
  id?: number
  userName?: string
  userProfile?: string
  userRole?: string
}>({})

const onEdit = (record: API.UserVO) => {
  editingKey.value = record.id ?? null
  editableRow.id = record.id
  editableRow.userName = record.userName
  editableRow.userProfile = record.userProfile
  editableRow.userRole = record.userRole
}

const onCancel = () => {
  editingKey.value = null
  editableRow.id = undefined
  editableRow.userName = undefined
  editableRow.userProfile = undefined
  editableRow.userRole = undefined
}

const onSave = async (id?: number) => {
  if (!id) return
  const payload: API.UserUpdateRequest = {
    id,
    userName: editableRow.userName,
    userProfile: editableRow.userProfile,
    userRole: editableRow.userRole,
  }
  const res = await updateUser(payload)
  if (res.data.code === 0) {
    message.success('保存成功')
    onCancel()
    fetchData()
  } else {
    message.error('保存失败，' + res.data.message)
  }
}

// 页面加载时请求一次
onMounted(() => {
  fetchData()
})

//  分页参数
const pagination = computed(() => {
  return {
    current: searchParams.pageNum ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => `共 ${total} 条`,
  }
})

//  表格变化处理
const doTableChange = (page: any) => {
  searchParams.pageNum = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

//  搜索
const doSearch=()=>{
  //  重置页码为1
  searchParams.pageNum = 1
  fetchData()
}

//  删除
const doDelete=async (id:number)=>{
  if (!id){
    return
  }
  const res =await deleteUser({id})
  if (res.data.code===0){
    message.success('删除成功')
    fetchData()
  }else {
    message.error('删除失败'+res.data.message)
  }
}
</script>
